package com.xinjian.jianba.service.impl;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xinjian.jianba.dao.dwmid.TicketsDao;
import com.xinjian.jianba.dao.dwmid.UserInfoDao;
import com.xinjian.jianba.dao.dwmid.UserMediaDao;
import com.xinjian.jianba.dto.ActivityFindOneDto;
import com.xinjian.jianba.dto.ActivityPersonIndexVo;
import com.xinjian.jianba.dto.ActivityWorkDto;
import com.xinjian.jianba.dto.AllRankDto;
import com.xinjian.jianba.dto.AllRankVo;
import com.xinjian.jianba.dto.TicketsDto;
import com.xinjian.jianba.dto.UserActivityDto;
import com.xinjian.jianba.enity.AcwardsEntity;
import com.xinjian.jianba.enity.AllRankEntity;
import com.xinjian.jianba.enity.UserActivityEntity;
import com.xinjian.jianba.enity.UserInfoEnity;
import com.xinjian.jianba.enity.UserMediaActivityEntity;
import com.xinjian.jianba.enity.UserMediaEnity;
import com.xinjian.jianba.exception.BusinessException;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.service.TicketsService;
import com.xinjian.jianba.utils.AliVideoUtil;
import com.xinjian.jianba.utils.Constants;
import com.xinjian.jianba.utils.QiNiuUtil;

import sun.misc.BASE64Decoder;
@Service
public class TicketsServiceImpl implements TicketsService{

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired 
	private TicketsDao ticketsDao;
	@Autowired
	private UserInfoDao userInfoDao;
	@Value("${activity.acLogo}")
	private String activityLogo;
	@Value("${jianba.vod.imgStr}")
	private String imgStr;
	@Override
	public int vote(TicketsDto ticketsDto) {
		int exists=ticketsDao.isJoin(ticketsDto.getMatchId());
		if(exists<1){
			throw new BusinessException(ResponseCode.ERROR, "该用户还未参加,无法给该用户投票");
		}
		redisTemplate.opsForValue().setIfAbsent(Constants.H5_ACTI_VOTE+ticketsDto.getUserId()+":"+ticketsDto.getMatchId()+":"+ticketsDto.getWorkId(), "0");
		Long num=redisTemplate.opsForValue().increment(Constants.H5_ACTI_VOTE+ticketsDto.getUserId()+":"+ticketsDto.getMatchId()+":"+ticketsDto.getWorkId(), 1);
		int result=0;
		UserInfoEnity userInfoEnity=userInfoDao.findById(ticketsDto.getUserId());
		if(userInfoEnity==null||userInfoEnity.getIs_register()==0){
			if(num<=1){
				 result=ticketsDao.vote(ticketsDto);
				}else{
					result=2;
				}
		}else{
			if(num>=2&&ticketsDto.getUserId()==ticketsDto.getMatchId()){
				throw new BusinessException(ResponseCode.ERROR, "自己一天最多给自己投一票");
			}
			if(num<=3&&ticketsDto.getUserId()!=ticketsDto.getMatchId()){
			 result=ticketsDao.vote(ticketsDto);
			}else{
				result=3;
			}
		}
		return result;
	}
	@Override
	public Long join(UserActivityDto userActivityDto) throws IOException {
		UserInfoEnity userInfoEnity=userInfoDao.findById(Long.parseLong(userActivityDto.getRegisterId()));
		if(userInfoEnity==null||userInfoEnity.getIs_register()==0){
			throw new BusinessException(ResponseCode.ERROR, "非注册用户,不能参加");
		}
		UserActivityEntity userActivityEntity=new UserActivityEntity();
		userActivityEntity.setRegisterId(Long.parseLong(userActivityDto.getRegisterId()));
		userActivityEntity.setActivityName(userActivityDto.getActivityName());
		userActivityEntity.setDetail(userActivityDto.getDetail());
		String base64Imgstr=userActivityDto.getBase64Imgstr();
		if(StringUtils.isBlank(base64Imgstr)){
			userActivityEntity.setActivityLogo(activityLogo);
		}else{
			@SuppressWarnings("restriction")
			byte[] imgByte = new BASE64Decoder().decodeBuffer(base64Imgstr);  
			if(getImageSize(imgByte)>9){
				throw new BusinessException(ResponseCode.ERROR, "图片大小不能大于9兆");
			}
			String address=QiNiuUtil.upOverWrite("ac_"+userActivityDto.getRegisterId()+".jpg", imgByte);
			userActivityEntity.setActivityLogo(address);
		}
		try{
		long userId=ticketsDao.join(userActivityEntity);
		}catch(DuplicateKeyException e){
			throw new BusinessException(ResponseCode.ERROR, "您已报名参加");
		}
		return userActivityEntity.getUserId();
	}
	@Override
	public int editor(UserActivityDto userActivityDto) throws IOException {
		String base64Imgstr=userActivityDto.getBase64Imgstr();
		int re=0;
		if(StringUtils.isBlank(base64Imgstr)){
			 re=ticketsDao.editor(userActivityDto);
		}else{
			@SuppressWarnings("restriction")
			byte[] imgByte = new BASE64Decoder().decodeBuffer(base64Imgstr);  
			if(getImageSize(imgByte)>9){
				throw new BusinessException(ResponseCode.ERROR, "图片大小不能大于9兆");
			}
			String address=QiNiuUtil.upOverWrite("ac_"+userActivityDto.getRegisterId()+".jpg", imgByte);
			String dbAcLogo=ticketsDao.findByRegisterId(Long.parseLong(userActivityDto.getRegisterId()));
			int lo=dbAcLogo.lastIndexOf("=");
			Integer index=null;
			if(lo>0){
			index=Integer.parseInt(dbAcLogo.substring(lo+1).trim())+1;
			}else{
				index=1;
			}
			dbAcLogo=address+"?m="+index;
			userActivityDto.setBase64Imgstr(dbAcLogo);
			re=ticketsDao.editorAndLogo(userActivityDto);
		}
		return re;
	}
	@Override
	public int workUp(ActivityWorkDto activityWorkDto) {
		int count=ticketsDao.isFull(activityWorkDto.getRegisterId());
		if(count>10){
			throw new BusinessException(ResponseCode.ERROR, "最多上传10个作品");
		}
		int num=ticketsDao.isUped(activityWorkDto.getVideoId());
		if(num>0){
			throw new BusinessException(ResponseCode.ERROR, "该视频已上传");
		}
		int result=0;
		try{
			UserMediaEnity userMediaEnity=new UserMediaEnity();
			userMediaEnity.setUid(activityWorkDto.getRegisterId());
			userMediaEnity.setAddress(activityWorkDto.getVideoId());
			userMediaEnity.setImgStr(activityWorkDto.getImgStr()==null?"":activityWorkDto.getImgStr());
			userMediaEnity.setMtype("activityVod");
			userMediaEnity.setType(1);
			userMediaEnity.setVideoId(activityWorkDto.getVideoId());
			result=ticketsDao.workUp(userMediaEnity);
		}catch(DuplicateKeyException e){
			UserMediaEnity userMediaEnity=new UserMediaEnity();
			userMediaEnity.setUid(activityWorkDto.getRegisterId());
			userMediaEnity.setAddress(activityWorkDto.getVideoId());
			userMediaEnity.setImgStr(activityWorkDto.getImgStr()==null?"":activityWorkDto.getImgStr());
			userMediaEnity.setMtype("activityVod");
			userMediaEnity.setType(1);
			userMediaEnity.setVideoId(activityWorkDto.getVideoId());
			result=ticketsDao.updateWork(userMediaEnity);
		}
		
		return result;
	}
	@Override
	public ActivityPersonIndexVo getPersonIndex(String registerId) {
		ActivityPersonIndexVo activityPersonIndexVo=ticketsDao.findPersonIndex(Long.parseLong(registerId));
		if(activityPersonIndexVo==null){
			throw new BusinessException(ResponseCode.ERROR, "无该选手参赛信息"); 
		}
		Map<String, Object> map=ticketsDao.getTicketsCountAndRank(Long.parseLong(registerId));
		String rank=(map==null||map.get("rank")==null)?"0":map.get("rank").toString();
		String ticketCount=(map==null||map.get("ticketCount")==null)?"0":map.get("ticketCount").toString();
		activityPersonIndexVo.setRank(subZeroAndDot(rank));
		activityPersonIndexVo.setTicketCount(subZeroAndDot(ticketCount));
		List<UserMediaActivityEntity> list=activityPersonIndexVo.getActivityWorks();
		//如果第一帧图片为空,则补上默认图片
		list.stream().forEach(userMediaActivityEntity ->{
			String imgStr=userMediaActivityEntity.getImgStr();
			if(StringUtils.isBlank(imgStr)){
				userMediaActivityEntity.setImgStr(this.imgStr);
			}
		});
		return activityPersonIndexVo;
	}
	@Override
	public AllRankVo allRank(AllRankDto allRankDto) {
		AllRankVo allRankVo=new AllRankVo();
		List<AllRankEntity> list=ticketsDao.allRank(allRankDto);
		int status=ticketsDao.isJoin(allRankDto.getRegisterId());
		if(status>0){
			allRankVo.setStatus(2l);//已参加比赛,注册app
		}else{
			UserInfoEnity userInfoEnity=userInfoDao.findById(allRankDto.getRegisterId());
			if(userInfoEnity==null||userInfoEnity.getIs_register()==0){
				allRankVo.setStatus(0l);//未注册app
			}else{
				allRankVo.setStatus(1l);//已注册app
			}
		}
		allRankVo.setList(list);
		return allRankVo;
	}
	@Override
	public AllRankEntity findOne(ActivityFindOneDto activityFindOneDto) {
		String activityNameOrActivityUid =activityFindOneDto.getActivityNameOrActivityUid();
		AllRankEntity allRankEntity=ticketsDao.findOne(activityFindOneDto);
		return allRankEntity;
	}
	/**
	   * 使用java正则表达式去掉多余的.与0
	   * @param s
	   * @return
	   */
	public  String subZeroAndDot(String s){
	    if(s.indexOf(".") > 0){
	      s = s.replaceAll("0+?$", "");//去掉多余的0
	      s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
	    }
	    return s;
	}
	@Override
	@Transactional(rollbackFor=Exception.class)
	public int delWork(Long workId) {
		ticketsDao.deleteWorkTickets(workId);
		String videoId=ticketsDao.findVideoIdByWorkId(workId);
		int result=ticketsDao.deleteUserMedia(workId);
		if(StringUtils.isNotBlank(videoId)){
			AliVideoUtil.deleteVideo(videoId);
		}
		return result;
	}
	@Override
	public List<AcwardsEntity> award() {
		List<AcwardsEntity> list=ticketsDao.getLuckPersons();
		return list;
	}
	
	/**
	 * 返回图片大小  单位m
	 * @param imageBytes
	 * @return
	 */
	public double getImageSize(byte[] imageBytes){
		double size=imageBytes.length;//字节
		return size/1024/1024;
		
		
	}
	
}
